package com.example.smartgreenhouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.smartgreenhouse.entity.SensitiveWord;
import com.example.smartgreenhouse.mapper.SensitiveWordMapper;
import com.example.smartgreenhouse.service.SensitiveWordService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SensitiveWordServiceImpl implements SensitiveWordService {
    private final SensitiveWordMapper sensitiveWordMapper;
    
    private List<String> activeWordsCache;
    private LocalDateTime lastUpdateTime;


    @PostConstruct
    public void init() {
        refreshCache();
    }

    @Scheduled(fixedRate = 5 * 60 * 1000)
    @Override
    public void refreshCache() {
        List<SensitiveWord> words = sensitiveWordMapper.selectList(
            new QueryWrapper<SensitiveWord>()
                .eq("is_active", true)
                .select("word")
        );

        this.activeWordsCache = words.stream()
            .map(SensitiveWord::getWord)
            .collect(Collectors.toList());
        this.lastUpdateTime = LocalDateTime.now();

    }

    @Override
    public LocalDateTime getLastUpdateTime() {
        return null;
    }

    @Override
    public boolean containsSensitiveWord(String text) {
        return false;
    }

    @Override
    public List<String> getActiveWords() {
        if (CollectionUtils.isEmpty(activeWordsCache)) {
            refreshCache();
        }
        return new ArrayList<>(activeWordsCache);
    }




}